"""
产品视图 - 门户网站
"""

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from pecco_site.models import Product, Category, ProductVariant
from ..serializers import ProductListSerializer, ProductDetailSerializer


class ProductListView(APIView):
    """
    产品列表 API
    
    GET /api/shop/products/?category=&search=&locale=en
    """
    permission_classes = []  # 公开访问
    
    def get(self, request):
        locale = request.GET.get('locale', 'en')
        category_slug = request.GET.get('category', '')
        search_query = request.GET.get('search', '')
        
        # 基础查询
        queryset = Product.objects.filter(is_active=True)
        
        # 分类筛选
        if category_slug:
            queryset = queryset.filter(categories__slug=category_slug)
        
        # 搜索
        if search_query:
            # 在翻译表中搜索
            queryset = queryset.filter(
                translations__locale=locale,
                translations__name__icontains=search_query
            ).distinct()
        
        # 获取产品数据
        products = []
        for prod in queryset.order_by('-created_at'):
            translation = prod.translations.filter(locale=locale).first()
            if translation:
                # 获取封面图
                cover_url = request.build_absolute_uri(prod.cover_image.url) if prod.cover_image else None

                # 获取悬停图
                hover_url = None
                if prod.hover_image:
                    hover_url = request.build_absolute_uri(prod.hover_image.url)

                # 获取价格范围
                price_range = prod.get_price_range()
                price_display = price_range['display'] if price_range else 'N/A'
                
                product_data = {
                    'id': prod.id,
                    'name': translation.name,
                    'short_desc': translation.short_desc or '',
                    'cover': cover_url,
                    'hover': hover_url,
                    'price': price_display,
                    'min_price': str(price_range['min']) if price_range else '0',
                    'max_price': str(price_range['max']) if price_range else '0',
                    'tags': {
                        'featured': prod.tag_featured,
                        'hot': prod.tag_hot,
                        'new': prod.tag_new,
                    },
                }
                products.append(product_data)
        
        return Response({
            'count': len(products),
            'results': products
        })


class ProductDetailView(APIView):
    """
    产品详情 API

    GET /api/shop/products/{id}/?locale=en
    """
    permission_classes = []  # 公开访问

    def get(self, request, pk):
        locale = request.GET.get('locale', 'en')

        try:
            product = Product.objects.prefetch_related(
                'variants', 'variants__option_values',
                'variants__option_values__option',
                'variants__option_values__translations',
                'variants__images'
            ).get(pk=pk, is_active=True)
        except Product.DoesNotExist:
            return Response(
                {'error': 'Product not found'},
                status=status.HTTP_404_NOT_FOUND
            )

        # 获取翻译
        translation = product.translations.filter(locale=locale).first()
        if not translation:
            return Response(
                {'error': 'Translation not found'},
                status=status.HTTP_404_NOT_FOUND
            )

        # 获取分类
        category = product.categories.first()
        category_name = ''
        if category:
            cat_trans = category.translations.filter(locale=locale).first()
            category_name = cat_trans.name if cat_trans else category.slug

        # 获取产品封面图片
        cover_images = []
        if product.cover_image:
            cover_images.append({
                'id': 'cover',
                'url': request.build_absolute_uri(product.cover_image.url),
                'alt_text': translation.name,
                'sort_order': 0,
            })
        if product.hover_image:
            cover_images.append({
                'id': 'hover',
                'url': request.build_absolute_uri(product.hover_image.url),
                'alt_text': translation.name,
                'sort_order': 1,
            })

        # 获取变体数据
        variants = []
        available_options = {}  # 存储所有可用的选项类型和值

        for variant in product.variants.filter(is_active=True):
            # 获取选项值
            option_values = []
            option_combination = {}

            for opt_val in variant.option_values.all():
                # 获取选项值的翻译
                opt_val_trans = opt_val.translations.filter(locale=locale).first()
                display_value = opt_val_trans.value if opt_val_trans else opt_val.value

                # 获取选项类型的翻译
                opt_trans = opt_val.option.translations.filter(locale=locale).first()
                option_name = opt_trans.name if opt_trans else opt_val.option.name

                option_data = {
                    'id': opt_val.id,
                    'option_type': opt_val.option.option_type,
                    'option_name': option_name,
                    'value': display_value,
                    'color_code': opt_val.color_code
                }
                option_values.append(option_data)
                option_combination[opt_val.option.option_type] = display_value

                # 收集可用选项
                if opt_val.option.option_type not in available_options:
                    available_options[opt_val.option.option_type] = {
                        'name': option_name,
                        'values': []
                    }

                # 添加选项值（避免重复）
                if not any(v['id'] == opt_val.id for v in available_options[opt_val.option.option_type]['values']):
                    available_options[opt_val.option.option_type]['values'].append({
                        'id': opt_val.id,
                        'value': display_value,
                        'color_code': opt_val.color_code
                    })

            # 获取变体图片
            variant_images = []
            for img in variant.images.all().order_by('sort_order'):
                variant_images.append({
                    'id': img.id,
                    'url': request.build_absolute_uri(img.image.url),
                    'alt_text': f"{translation.name} - {' '.join(option_combination.values())}",
                    'sort_order': img.sort_order,
                    'is_primary': img.is_primary
                })

            variants.append({
                'id': variant.id,
                'sku': variant.sku,
                'option_values': option_values,
                'option_combination': option_combination,
                'price': str(variant.price),
                'stock': variant.stock,
                'product_details': variant.product_details,
                'images': variant_images
            })

        # 构建响应数据
        data = {
            'id': product.id,
            'name': translation.name,
            'short_desc': translation.short_desc or '',
            'description': translation.rich_desc or '',
            'category_name': category_name,
            'usage': product.usage or '',
            'tags': {
                'featured': product.tag_featured,
                'hot': product.tag_hot,
                'new': product.tag_new,
            },
            'cover_images': cover_images,
            'variants': variants,
            'available_options': available_options,
            'default_product_details': translation.default_product_details or '',
            'general_specifications': translation.general_specifications or '',
        }

        return Response(data)

